package com.abc.robot01.activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.lifecycleScope
import androidx.navigation.ui.AppBarConfiguration
import com.abc.robot01.R
import com.abc.robot01.activity.FangAnActivity.WebAppInterface
import com.abc.robot01.databinding.ContentMainBinding
import com.abc.robot01.fragment.PicFragment
import com.abc.robot01.fragment.VideoFragment
import com.abc.robot01.retrofit.bean.ARTICLE
import com.abc.robot01.retrofit.bean.DESIGN_PACKAGE
import com.abc.robot01.retrofit.bean.GlobalState
import com.abc.robot01.retrofit.bean.LocalConfig
import com.abc.robot01.retrofit.bean.VIDEO
import com.abc.robot01.view.enableFaClick
import com.abc.robot01.view.enableInfoClick
import com.abc.robot01.view.enableSpClick
import com.abc.robot01.vivemodel.HomePageProductViewmodel
import com.abc.robot01.vivemodel.HomePageViewModel
import com.abc.robot01.vivemodel.Robot
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class BaseActivity : BaseVoiceActivity() {
    private val handler = Handler(Looper.getMainLooper())
    private lateinit var appBarConfiguration: AppBarConfiguration
    lateinit var binding: ContentMainBinding

    private val viewModel2: HomePageViewModel by viewModels()

    override fun onPause() {
        Log.e("BaseActivity","onPause");
        super.onPause()

    }

    override fun onDestroy() {
        Log.e("BaseActivity","onDestroy");
        super.onDestroy()
    }

    override fun onNewIntent(intent: Intent) {
        Log.e("BaseActivity","onNewIntent");
        super.onNewIntent(intent)
    }


    //悬浮窗在layout文件里面.
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("BaseActivity","onCreate");
        binding = ContentMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        lifecycleScope.launch {
            pollNotce(viewModel2=viewModel2)
        }

        findViewById<ConstraintLayout>(R.id.root1).translationX = GlobalState.x;
        findViewById<ConstraintLayout>(R.id.root1).translationY = GlobalState.y;
        findViewById<ComposeView>(R.id.root2).visibility = GlobalState.visible;



        //方案库
        Log.e("getDesignPackages", "userId:${Robot.userId}");
        Log.e("getDesignPackages", "companyId:${Robot.companyId}");
        Log.e("getDesignPackages", "accessToken:${Robot.accessToken}");

        enableFaClick {
            startActivity<FangAnKuActivity>()
        }

        enableSpClick {
            startActivity<ShangPinKuActivity>()
        }

        enableInfoClick() {
            startActivity<SysMessageActivity>()
        }

        //首页商品列表
        val left: ComposeView = findViewById(R.id.left_content)
        left.setContent {
            ProductList(viewModel)
        }

        val composeView: ComposeView = findViewById(R.id.compose_view)

        val composeView2: ComposeView = findViewById(R.id.compose_view2)

        composeView2.setContent {
            var isDialogVisible by remember { viewModel2.isDialogVisible}
            val name by remember { viewModel2.noticeName}
            val time by remember { viewModel2.noticeTime}

            // Trigger Dialog visibility logic
            if (isDialogVisible) {
                CustomToastDialog(
                    name = name,
                    time = time,
                    thumbnail = viewModel2.thumbnail9.value,
                    id = viewModel2.dataId9.value,
                    url = viewModel2.pageUrl9.value,
                    onViewClick = { isDialogVisible = false },
                    onLaterClick = { isDialogVisible = false },
                    onDismiss = { isDialogVisible = false }
                )
            }
        }

        // Set Compose content
        composeView.setContent {
            Log.e(TAG, " composeView.setContent")
            // Composable content goes here
            Box(
                modifier = Modifier.fillMaxSize()
            ) {
//                if (fullScreen.not()) {
                //首先是Pager
                TopPager(viewModel2, onTabSelected = ::onTabSelected)
//                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        Log.e("BaseActivity","onResume");
        findViewById<ConstraintLayout>(R.id.root1).translationX = GlobalState.x;
        findViewById<ConstraintLayout>(R.id.root1).translationY = GlobalState.y;
        findViewById<ComposeView>(R.id.root2).visibility = GlobalState.visible;
    }



    fun fullScreen(f: Boolean) {
        viewModel2.fullScreen.value = f
        if (f) {
            findViewById<View>(R.id.floating).visibility = View.INVISIBLE
            findViewById<View>(R.id.left).visibility = View.INVISIBLE
        } else {
            findViewById<View>(R.id.floating).visibility = View.VISIBLE
            findViewById<View>(R.id.left).visibility = View.VISIBLE
        }
    }

    override fun handleVoiceCommand(asr: String): Boolean {
        if (asr.contains("商品")) {
            startActivity<ShangPinKuActivity> { }
            playTTS("好的")
            return true
        } else
            if (asr.contains("信息")) {
                startActivity<SysMessageActivity> { }
                playTTS("好的")
                return true
            } else
                if (asr.contains("方案")) {
                    startActivity<FangAnKuActivity> { }
                    playTTS("好的")
                    return true
                }
        return false
    }

    private val pagerState = object : PagerState() {
        override val pageCount: Int
            get() = viewModel2.list.size
    }

    fun playPrevious(index: Int) {
        Log.e(TAG, "playPrevious:${index}");
        for (i in index - 1 downTo 0) {
            Log.e(TAG, "playPrevious for000 :${i}");
            if (viewModel2.list[i].type == VIDEO) {
                Log.e(TAG, "playPrevious for:${i}");
                lifecycleScope.launch {
                    pagerState.scrollToPage(i)
                }
                return
            }
        }
    }

    fun playNext(index: Int) {
        Log.e(TAG, "playNext:${index}");
        viewModel2.list.forEachIndexed { index2, item ->
            if (index2 > index) {
                if (item.type == VIDEO)
                    lifecycleScope.launch {
                        Log.e(TAG, "playNext for:${index2}");
                        pagerState.scrollToPage(index2)
                    }
                return@forEachIndexed
            }
        }
    }

    @Composable
    fun TopPager(viewModel: HomePageViewModel, onTabSelected: (String, String) -> Unit) {
        Log.e(TAG, "TopPager")
        val configs = viewModel.configs.collectAsState()
        viewModel.list.clear()
        configs.value.forEach {
            when (it.configType) {
                DESIGN_PACKAGE -> it.configs.forEach {
                    Log.e(TAG, "DESIGN_PACKAGE: " + it.renderUrl)
                    viewModel.list += LocalConfig(
                        type = DESIGN_PACKAGE,
                        url = it.renderUrl,
                        it.id,
                        it.robotId,
                        designPackageId =  it.designPackageId!!
                    );
                }

                VIDEO -> {
                    it.configs.forEach {
                        viewModel.list += LocalConfig(
                            type = VIDEO,
                            url = it.fileUrl,
                            configId = it.id,
                            robotId = it.robotId
                        );
                    }
                }

                ARTICLE -> {
                    it.configs.forEach {
                        viewModel.list += LocalConfig(
                            type = "ARTICLE",
                            url = it.fileUrl,
                            configId = it.id,
                            robotId = it.robotId
                        );
                    }
                }
            }
        }

//        viewModel.currentPage = pagerState.currentPage;

        if (viewModel.list.size == 0) return

        Box(modifier = Modifier.fillMaxSize(),) {

            val context = LocalContext.current

            // 用 Map 存储 WebView 实例，每个 URL 对应一个 WebView
            val webViewMap = remember { mutableStateOf(mutableMapOf<String, WebView>()) }

            // 生命周期观察，处理 onPause 时的 WebView 操作
            DisposableEffect( context) {
                val observer = LifecycleEventObserver { _, event ->
                    if (event == Lifecycle.Event.ON_PAUSE) {
                        // 获取 WebView 并调用相关方法
                        webViewMap.value.forEach{
                            it.value.evaluateJavascript("javascript:closeMusic();", null)
                        }
                    } else
                    if (event == Lifecycle.Event.ON_RESUME) {
                        // 获取 WebView 并调用相关方法
                        webViewMap.value.forEach{
                            it.value.evaluateJavascript("javascript:openMusic();", null)
                        }
                    }
                }

                // 添加生命周期观察者
                val lifecycleOwner = context as? ComponentActivity
                lifecycleOwner?.lifecycle?.addObserver(observer)

                // 清理工作
                onDispose {
                    lifecycleOwner?.lifecycle?.removeObserver(observer)
                }
            }

            // 页面滑出视图时执行的操作
            LaunchedEffect(key1 = pagerState.currentPage) {
                // 如果当前页面不等于 `page` 表示它滑出可视区域
                    Log.e(TAG,"pagerState.currentPage  ${pagerState.currentPage}")
                webViewMap.value.keys.forEach {
                    Log.e(TAG,"pagerState webViewMap key:${it}")
                }
                //找出当前Tab的type和url，把和当前url不一样的webViewMap的webview全部暂停播放

                val url = viewModel.list[pagerState.currentPage].url

                Log.e(TAG,"pagerState currentPage url $url")

                webViewMap.value.filter {
                    it.key != url
                }.forEach { t, u ->
                    Log.e(TAG,"pagerState 暂停: $t")
                    u.evaluateJavascript("javascript:closeMusic();", null)
                }

                //如果当前是webview，则开始播放;
                delay(1000)
                webViewMap.value.filter{
                    it.key ==url
                }.forEach { t, u ->
                    Log.e(TAG,"pagerState 开始播放: $t")
                    u.evaluateJavascript("javascript:openMusic();", null)
                }
            }
            Log.e(TAG, "before HorizontalPager" );
            HorizontalPager(state = pagerState, userScrollEnabled = false) { page ->
                val current = viewModel.list[page]
                Log.e(TAG, "切换到："+current.url);
                onTabSelected(current.robotId, current.configId)
                when (current.type) {
                    "DESIGN_PACKAGE" -> {
                        // 根据 URL 获取对应的 WebView，如果没有则创建一个新的
                        val webView = webViewMap.value.getOrPut(current.url) {
                            createWebView(current.url+"&showType=5",current.designPackageId)
                        }

                        AndroidView(factory = { context ->
                            Log.e("DESIGN_PACKAGE", "webview");
                            webView.also {
//                                it.evaluateJavascript("javascript:openMusic();", null)

                            }
                        },
                            )
                    }

                    "VIDEO" -> {
                        FragmentContainer(VideoFragment(current.url, index = page))
                    }

                    "ARTICLE" -> {
                        FragmentContainer(PicFragment(current.url))
                    }
                }
            }
            Log.e(TAG, "after HorizontalPager");
            Column(
                modifier = Modifier.fillMaxSize(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Spacer(modifier = Modifier.height(30.px))
                TABIndexer(viewModel)

            }
        }
    }

    // 创建并初始化 WebView 的函数
    private fun createWebView(url: String,designPackageId:String): WebView {
        return WebView(this).apply{
            layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            clearCache(true)
            settings.javaScriptEnabled = true
            settings.cacheMode = WebSettings.LOAD_NO_CACHE
            settings.domStorageEnabled = true
            webViewClient = WebViewClient()
            loadUrl(url) // 设置需要加载的 URL
            Log.e(TAG, "WebView loadUrl: $url");
            addJavascriptInterface(WebAppInterface(context = this@BaseActivity,designPackageId!!),"AndroidInterface")
//            loadUrl("https://720.xmlights.com/720show/preview?recordId=ff80808189b0a1f20189b49297e10e20") // 设置需要加载的 URL
        }
    }

    @Composable
    fun TABIndexer(viewModel: HomePageViewModel) {
        val coroutineScope = rememberCoroutineScope()
        val fullScreen by remember {
            viewModel2.fullScreen
        }
        if (fullScreen.not()) {
            Row {
                viewModel.list.forEachIndexed { index, localConfig ->
                    val selected = pagerState.currentPage == index
                    Box(
                        modifier = Modifier
                            .clickable {
                                coroutineScope.launch {
                                    pagerState.scrollToPage(index)
                                    onTabSelected(localConfig.robotId, localConfig.configId)
                                }
                            }
                            .padding(0.dp)
                            .background(
                                if (selected) Color(0xFF90EE90) else Color(0xFFADD8E6),
                                shape = RoundedCornerShape(0.dp)
                            ) // Custom background and shape
                            .size(width = 100.px, height = 30.px)) {
                    }
                    if (viewModel.list.lastIndex != index)
                        Spacer(modifier = Modifier.width(24.px))
                }
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ProductItem(commodityTreeName: String, pic: String?, id: String) {
        Column(modifier = Modifier.clickable {
            startActivity<XiangQingActivity> {
                putExtra("id", id)
            }
        }) {
//                if(pic != null) {
            GlideImage(
                model = pic ?: R.drawable.sp001,
                contentDescription = "",
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .size(192.px, 192.px),
            )
//                }
//                else
//                Image(
//                    painter = painterResource(id = R.drawable.sp001),
//
//                    contentDescription = "Image",
//                    contentScale = ContentScale.Crop,
//                )
            Spacer(modifier = Modifier.height(14.px))
            Text(
                text = commodityTreeName,
                color = Color.White,
                fontSize = 24.mysp,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
            )
        }
    }

    //商品列表
    @Composable
    fun ProductList(viewModel: HomePageProductViewmodel) {
        val configs = viewModel.configs.observeAsState().value ?: return
//        if (configs.code != 200)
//            return
        LazyVerticalGrid(
            contentPadding = PaddingValues(top = 30.px),
            horizontalArrangement = Arrangement.spacedBy(30.px),
            verticalArrangement = Arrangement.spacedBy(30.px),
            columns = GridCells.Fixed(4), // 2 columns in the grid
            modifier = Modifier
                .fillMaxSize()
                .padding(start = 0.px)
//                .background(
//                    Brush.horizontalGradient(
//                    colors = listOf(
//                        Color(0xFF000000).copy(alpha = 0.8f), // 黑色，透明度 100%
//                        Color(0xFF000000).copy(alpha = 0.8f), // 黑色，透明度 60%
//                        Color(0xFF000000).copy(alpha = 0.0f)  // 黑色，透明度 20%
//                    )
//                ))
        ) {
            items(configs.list) { item ->
                ProductItem(item.name, item.thumbnail, item.commodityId)
            }
        }
    }

    private val viewModel: HomePageProductViewmodel by viewModels()





    private fun onTabSelected(robotId: String, tab: String) {
        viewModel.fetchData(robotId = robotId, homePageConfigId = tab);
    }

    @Composable
    fun FragmentContainer(fragment: Fragment) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragment_container, fragment)
        fragmentTransaction.commit()
    }

    companion object {
        val TAG = "BaseActivity"
    }

}



